package com.jsd.demo1;

import jdk.nashorn.internal.ir.CallNode;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author jsd
 */
public class C {

    public static void main(String[] args) {
        D d = new D();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    d.inNumber();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "生成者A").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    d.inNumber();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "生成者B").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    d.deNumber();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "消费者C").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    d.deNumber();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "消费者D").start();
    }
}

class D {

    private int number = 0;

    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();

    public void inNumber () throws InterruptedException {

        try {
            lock.lock();
            while (number != 0) {
                condition.await();
            }

            number++;
            System.out.println(Thread.currentThread().getName() + "=>生成了" + number + "个");

            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }

    public void deNumber () throws InterruptedException {
        try {
                lock.lock();
            while (number == 0) {
                condition.await();
            }
            number--;
            System.out.println(Thread.currentThread().getName() + "=>还剩下" + number + "个");
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

}
